import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'

export const history =
  import.meta.env.VITE_ROUTER_HISTORY === 'hash'
    ? createWebHashHistory(import.meta.env.VITE_PUBLIC_PATH)
    : createWebHistory(import.meta.env.VITE_PUBLIC_PATH)

const Layouts = () => import('@/layouts/index.vue')

export const constantRoutes = [
  {
    path: '/',
    redirect: '/order',
  },
  {
    path: '/order',
    name: 'Order',
    component: Layouts,
    redirect: '/order/list',
    meta: {
      title: '订单',
      hidden: true,
    },
    children: [
      {
        path: 'list',
        name: 'OrderList',
        component: () => import('@/views/order/index.vue'),
        meta: {
          title: '订单列表',
          hidden: true,
        },
      },
    ],
  },
  {
    path: '/payment',
    name: 'Payment',
    redirect: '/payment/:id',
    component: Layouts,
    meta: {
      title: '订单支付',
      hidden: true,
    },
    children: [
      {
        path: ':id',
        name: 'PaymentPage',
        component: () => import('@/views/payment/index.vue'),
        meta: {
          title: '订单支付',
          hidden: true,
        },
      },
    ],
  },
  {
    path: '/403',
    component: () => import('@/views/error-page/403.vue'),
    meta: {
      hidden: true,
    },
  },
  {
    path: '/404',
    component: () => import('@/views/error-page/404.vue'),
    meta: {
      hidden: true,
    },
    alias: '/:pathMatch(.*)*',
  },
  {
    path: '/login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      title: 'Login',
      hidden: true,
      licenseFree: true,
    },
  },
]

export const dynamicRoutes = []

const router = createRouter({
  history,
  routes: constantRoutes,
})

/**
 * Resets the router by removing all routes with a name that have a roles array.
 * If removing a route fails, the browser is forcefully reloaded.
 */
export function resetRouter() {
  // Note: Dynamic routes must have a name property to be completely removed.
  try {
    // Iterate over all routes
    router.getRoutes().forEach(route => {
      const { name, meta } = route

      // Check if the route has a name and a roles array
      if (name && meta.roles?.length) {
        // Remove the route if it exists
        if (router.hasRoute(name)) {
          router.removeRoute(name)
        }
      }
    })
  } catch {
    // If removing a route fails, reload the browser
    // A better solution would be to avoid the need to reload the browser
    window.location.reload()
  }
}

export default router
